<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2017/12/15
 * Time: 11:00
 */

namespace Biz\service;


use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\ShopCompanyInfo as mShopCompanyInfo;
use Biz\model\ShopPersonalInfo as mShopPersonalInfo;
use Biz\model\ShopSecurityDeposit as mShopSecurityDeposit;
use Biz\model\ShopSecurityDepositLog as mShopSecurityDepositLog;
use Biz\module\Classes\adm\SecurityDepositSearch as clsAdmSecurityDepositSearch;
use Biz\module\Classes\SecurityDeposit as clsSecurityDeposit;
use Biz\tools\Amount;
use Doraemon\tools\Log as tLog;
use Intervention\Image\ImageManagerStatic as ImageManager;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\tools\ImgUrl;
use League\Flysystem\Exception;
use Hhzbeads\Img\ImgUpload;

/**
 * @deprecated
 */
class ShopSecurityDeposit
{
    use _Async;

    /**
     * 通知管理员已支付保证金
     */
    public static function mgtNoticeManagePaid($uid)
    {
        mShopSecurityDeposit::mgtNoticeManagePaid($uid);
    }


    public static function getDepositInfo($uid)
    {
        $info = mShopSecurityDeposit::getInfo($uid);

        return $info;
    }

    public static function mgtCheckNoticeManagePaid($shopId)
    {
        $info = mShopSecurityDeposit::getInfo($shopId);

        return isset($info['status']) ? $info['status'] == mShopSecurityDeposit::STATUS_WAIT_CONFIRM : false;
    }


    public static function admSearchShopDepositLog($params, $limit)
    {
        $search = new clsAdmSecurityDepositSearch($params, $limit);

        return [
            'total' => $search->getCount(),
            'list' => $search->getList()
        ];;


    }


    /**
     * 管理员对保证金进行增减操作
     */
    public static function admOperatDeposit($uid, $adminUid, $type, $amount, $remark, $transNumber, $transTime)
    {

        try {

            if (empty($remark)) {
                $remark = '管理员操作';
            }

            $res = mShopSecurityDeposit::action(function () use ($uid, $type, $amount, $adminUid, $remark, $transNumber, $transTime) {
                $cls = new clsSecurityDeposit();
                $logId = 0;
                //判断类型
                switch ($type) {
                    case mShopSecurityDepositLog::TYPE_SHOP_PAY_DEPOSIT:
                        //操作余额

                        $logId = $cls->operateBalance($uid, $amount, $type, $transNumber, $transTime, 'manage', $adminUid, $remark);

                        $depositInfo = mShopSecurityDeposit::getInfo($uid);

                        if (($depositInfo['balance'] + $amount) >= $depositInfo['amount']) {
                            $ret = mShopSecurityDeposit::update(['status' => mShopSecurityDeposit::STATUS_COMPLETE_DELIVERY], ['uid' => $uid]);
                        }
                        break;
                    case mShopSecurityDepositLog::TYPE_SHOP_VIOLATION:

                        //操作余额
                        $amount = 0 - abs($amount);

                        $logId = $logId = $cls->operateBalance($uid, $amount, $type, $transNumber, $transTime, 'manage', $adminUid, $remark);
                        break;
                    case mShopSecurityDepositLog::TYPE_SHOP_ADD_GOODS_AMOUNT://保证金补货款
                    case mShopSecurityDepositLog::TYPE_SHOP_CLOSE_BACK_AMOUNT://关店退保证金

                        //操作余额
                        $amount = 0 - abs($amount);

                        $logId = $cls->operateBalance($uid, $amount, $type, $transNumber, $transTime, 'manage', $adminUid, $remark);
                        break;
                }
                return $logId;
            });
            if ($res) {
                return $res;
            } else {
                throw new \Exception('管理员操作保证金失败');
            }


        } catch (\Exception $e) {

            tLog::warning("管理员操作保证金失败", [
                'uid' => $uid,
                'adminUid' => $adminUid,
                'type' => $type,
                'amount' => $amount,
                'remark' => $remark,
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }

    }

    /**
     * 管理员对保证金进行设置
     */
    public static function admUpdateDepositAmount($uid, $adminUid, $amount, $toStatus = null)
    {
        try {
            if ($amount <= 0) {
                throw new \Exception('请正确设置保证金额度');
            }

            $type = mShopSecurityDepositLog::TYPE_SHOP_ADMIN_SET_AMOUNT;

            $remark = '管理员设置保证金额度';


            mShopSecurityDeposit::action(function () use ($uid, $type, $amount, $adminUid, $remark, $toStatus) {
                $cls = new clsSecurityDeposit();

                //判断类型
                switch ($type) {
                    case mShopSecurityDepositLog::TYPE_SHOP_ADMIN_SET_AMOUNT:
                        $cls->operateAmount($uid, $amount, 'manage', $adminUid, true);

                        $ret = mShopSecurityDeposit::update(['status' => $toStatus], ['uid' => $uid]);

                        if ($ret->errorCode() !== '00000') {
                            throw new \Exception('数据库操作错误');
                        }

                        break;
                }

            });


        } catch (\Exception $e) {
            tLog::warning(" 管理员设置保证金额度", [
                'uid' => $uid,
                'adminUid' => $adminUid,
                'type' => mShopSecurityDepositLog::TYPE_SHOP_ADMIN_SET_AMOUNT,
                'amount' => $amount,
                'remark' => '管理员设置保证金额度',
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);

            throw $e;
        }
    }


    public static function mgtGetShopDepositLog($shopId, $startTime, $endTime, $limit)
    {
        $where = ['shop_id' => $shopId, 'status' => mShopSecurityDepositLog::STATUS_PROCESSED];
        if ($startTime && $endTime) {
            $where['addtime[>=]'] = $startTime;
            $where['addtime[<=]'] = $endTime;
        }
        $list = mShopSecurityDepositLog::getLogs($where, $limit, ['addtime' => 'DESC'], true);
        foreach ($list as &$row) {
            $row['admin_name'] = '好好住';
        }
        $count = mShopSecurityDepositLog::getLogsCount($where);
        return ['list' => $list, 'count' => $count];
    }

    /**
     * 生成保证金收据图片
     * @param array $logInfoList 保证金更新记录
     * @return array
     * @throws
     */
    public static function buildDepositImg(array $logInfoList)
    {
        $shopIds = array_column($logInfoList, 'shop_id');
        $basicInfoList = mShopBasicInfo::getShopInfoList($shopIds);
        $personalShopIds = [];
        $companyShopIds = [];
        foreach ($basicInfoList as $shopId => $row) {
            if ($row['type'] == mShopBasicInfo::TYPE_PERSONAL) {
                array_push($personalShopIds, $row['shop_id']);
            }
            if ($row['type'] == mShopBasicInfo::TYPE_COMPANY) {
                array_push($companyShopIds, $row['shop_id']);
            }
        }
        $personalList = mShopPersonalInfo::getInfoList($personalShopIds);
        $companyList = mShopCompanyInfo::getInfoList($companyShopIds);
        $basePath = '/data/wwwroot/g_biz/source/deposit';
        $fontFile = $basePath . '/SYFONT/NotoSansHans-Medium.otf';
        if (!file_exists($basePath . '/receipt.png')) {
            throw new Exception('不存在模板图片:' . $basePath . '/路径中');
        }
        $picIds = [];
        foreach ($logInfoList as $logInfo) {
            $shopId = $logInfo['shop_id'];
            if (in_array($shopId, $personalShopIds)) {
                $name = $personalList[$shopId]['realname'] . '-' . $basicInfoList[$shopId]['name'];
            } else if (in_array($shopId, $companyShopIds)) {
                $name = $companyList[$shopId]['name'] . '-' . $basicInfoList[$shopId]['name'];
            }

            $transNum = 'hhz-' . $logInfo['trans_number'];
            $date = date('Y年n月j日', strtotime($logInfo['trans_time']));
            $remark = $logInfo['remark'];
            $amount = abs($logInfo['balance']);
            $amount = number_format($amount, 2, '.', '');
            $amountRMB = Amount::toChinaRmb($amount);
            $type = $logInfo['type'];
            $tempImg = '';
            if ($type == mShopSecurityDepositLog::TYPE_SHOP_PAY_DEPOSIT) {//收据
                $tempImg = $basePath . '/receipt.png';
            } else if (in_array($type, [mShopSecurityDepositLog::TYPE_SHOP_VIOLATION, mShopSecurityDepositLog::TYPE_SHOP_ADD_GOODS_AMOUNT])) {//扣款
                $tempImg = $basePath . '/withhold.png';
            }
            if ($tempImg && file_exists($tempImg)) {
                ini_set('max_execution_time', 500);
                ImageManager::configure(array(
                    'driver' => 'imagick'
                ));
                $final = ImageManager::make($tempImg);
                $final->text($transNum, 470, 86, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(14);
                    $font->color("#000000");
                    $font->align("center");
                    $font->valign("top");
                });
                $final->text($date, 468, 112, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(14);
                    $font->color("#000000");
                    $font->align("center");
                    $font->valign("top");
                });
                $final->text($name, 140, 163, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(16);
                    $font->color("#000000");
                    $font->align("left");
                    $font->valign("top");
                });
                $final->text($remark, 140, 214, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(16);
                    $font->color("#000000");
                    $font->align("left");
                    $font->valign("top");
                });
                $final->text($amountRMB, 141, 268, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(16);
                    $font->color("#000000");
                    $font->align("left");
                    $font->valign("top");
                });
                $final->text($amount, 397, 268, function ($font) use ($fontFile) {
                    $font->file($fontFile);
                    $font->size(16);
                    $font->color("#000000");
                    $font->align("left");
                    $font->valign("top");
                });
                $rand = md5(rand(1, 1000) . "_" . rand(1, 1000) . "_" . time());
                $filePath = sys_get_temp_dir() . "/deposit_" . $rand . ".png";
                $final->save($filePath);
                if (file_exists($filePath)) {
                    $picResult = ImgUpload::upload(ImgUpload::APPTYPE_BIZ, $filePath);
                    $picId = ($picResult && $picResult['ori_pic_id']) ? $picResult['ori_pic_id'] : '';
                    unlink($filePath);
                    $ret = mShopSecurityDepositLog::update(['img' => $picId], ['id' => $logInfo['id']]);
                    if ($ret->errorCode() !== '00000') {
                        throw new Exception('生成收据失败');
                    }
                    array_push($picIds, $picId);
                }
            } else {
                throw new Exception('不存在模板文件:' . $basePath . '路径中;保证金收据类型：' . $type);
            }
        }
        return $picIds;
    }

}